package com.cmii.sjw.department.control.jsc.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

/**
 * Copyright (C), 2010-2021
 * Description：
 *
 * @author fangliu
 * @version 1.0.0
 * @date 2021/10/28 14:54
 */
public class Sm4Utils {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "UTF-8";

    public static final String ALGORITHM_NAME = "SM4";

    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    public static String encryptEcb(byte[] hexKey, String paramStr) throws Exception {
        String cipherText = null;
        byte[] keyData = hexKey;
        byte[] srcData = paramStr.getBytes(ENCODING);
        byte[] cipherArray = encrypt_Ecb_Padding(keyData.toString(), srcData);
        cipherText = Base64.getEncoder().encodeToString(cipherArray);
        return cipherText;
    }

    public static byte[] encrypt_Ecb_Padding(String secret, byte[] data) throws Exception {
        String encrypt = encrypt(secret);
        byte[] keys = ByteUtils.fromHexString(encrypt);
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, keys);
        return cipher.doFinal(data);
    }

    public static String decryptEcb(byte[] hexKey, String cipherText) throws Exception {
        String decryptStr = "";
        byte[] keyData = hexKey;
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] srcData = decrypt_Ecb_Padding(keyData.toString(), cipherData);
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }

    public static byte[] decrypt_Ecb_Padding(String secret, byte[] cipherText) throws Exception {
        String encrypt = encrypt(secret);
        byte[] keys = ByteUtils.fromHexString(encrypt);
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, keys);
        return cipher.doFinal(cipherText);
    }

    public static boolean verifyEcb(byte[] hexKey, String cipherText, String paramStr) throws Exception {
        boolean flag = false;
        byte[] keyData = hexKey;
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] decryptData = decrypt_Ecb_Padding(keyData.toString(), cipherData);
        byte[] srcData = paramStr.getBytes(ENCODING);
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    public static String encrypt(String input) {
        try {
            // 创建 MD5 摘要算法实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将输入字符串转换为字节数组
            byte[] inputBytes = input.getBytes();

            // 计算摘要
            byte[] hashBytes = md.digest(inputBytes);

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte hashByte : hashBytes) {
                String hex = Integer.toHexString(0xFF & hashByte);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String data = "张三";
        String secret = "4b8bafd5a1d7199c949cf09fd0f4f01342417bebb50c05787dac56a42e8d02363ecd2f06e8d434217810ade1cc09bb18";
        Encoder encoder = Base64.getEncoder();
        String encode = encoder.encodeToString(encrypt_Ecb_Padding(secret, data.getBytes()));
        System.out.println("加密结果2：" + encode);
        Decoder decoder = Base64.getDecoder();
        String decrypt = new String(decrypt_Ecb_Padding(secret, decoder.decode("UoJtNUER7OKjIq1M2M1cNg==")));
        System.out.println("解密结果2：" + decrypt);
    }
}